package v1.com.autoresource.aop;

import v1.com.autoresource.config.DynamicDataResourceHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * @ProjectName: learning
 * @Package: com.autoresource.aop
 * @ClassName: SelectDataSourceAspect
 * @Description:
 * @Date: 2021/11/5 10:15 下午
 * @Version: 1.0
 */
@Aspect
public class SelectDataSourceAspect {

    @Pointcut("@annotation(v1.com.autoresource.aop.SelectDataSource)")
    public void selectDataPointcut() {

    }

    @Around("selectDataPointcut()")
    public Object verifyRoleExecuteCommand(ProceedingJoinPoint pjp) throws Throwable {
        // 获取当前拦截方法的对象
        MethodSignature msig = (MethodSignature) pjp.getSignature();
        Method targetMethod = pjp.getTarget().getClass().getDeclaredMethod(msig.getName(), msig.getMethod().getParameterTypes());

        SelectDataSource annotation = targetMethod.getAnnotation(SelectDataSource.class);

        if (annotation == null) {
            Class<?>[] inters = pjp.getTarget().getClass().getInterfaces();
            for (Class<?> inter : inters) {
                Method targetInterMethod = inter.getDeclaredMethod(msig.getName(), msig.getMethod().getParameterTypes());
                annotation = targetInterMethod.getAnnotation(SelectDataSource.class);
                if (annotation != null) {
                    break;
                }
            }
        }
        if (annotation == null) {
            DynamicDataResourceHolder.selectMasterDataResource();
        } else {
            String dataSource = annotation.dataSource();
            if (dataSource.equals(DynamicDataResourceHolder.MASTER_DATA_SOURCE)) {
                DynamicDataResourceHolder.selectMasterDataResource();
            } else if (dataSource.equals(DynamicDataResourceHolder.SLAVE_DATA_SOURCE)) {
                DynamicDataResourceHolder.selectSlaveDataResource();
            }
        }
        return pjp.proceed();
    }

}


